﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using TCG.Engine.Core;

namespace TCG.Engine.Libraries
{
    public class FileDeckLibrary : IDeckLibrary
    {
        string file;
        public FileDeckLibrary(string file)
        {
            this.file = file;
        }
        Dictionary<string, DeckInfo> decks;

        public Dictionary<string, DeckInfo> Decks
        {
            get
            {
                if (decks == null)
                {
                    decks = LoadDecks();
                }
                return decks;
            }
        }

        private Dictionary<string, DeckInfo> LoadDecks()
        {
            using (var fs = File.OpenRead(file))
            {
                XmlSerializer s = new XmlSerializer(typeof(DecksInfo));
                var result = (DecksInfo)s.Deserialize(fs);
                return result.ToDictionary(di => di.Id, di => di);
            }
        }

        public Deck CreateDeck(string id)
        {
            Deck result = new Deck();
            var cards = Env.Get<ICardLibrary>();

            foreach (var ci in Decks[id].Cards)
            {
                result.AddCard(cards.Cards[ci.Id], ci.Count);
            }

            return result;
        }
    }
}
